# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/5/14 11:52 上午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : SerialReadWithExecute.py
# @Software: PyCharm

import os
import time

import SerialReader
from threading import Thread, Timer


def write_log(ser):
    # 获取日志重定向位置，在桌面下创建logs文件夹，日志将存在该文件夹下
    desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
    file_path = os.path.join(desktop_path, 'logs')
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    ex_time = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time()))
    log_path = os.path.join(file_path, 'pycharm_logs', f'rtos_log_{ex_time}.log')

    print(log_path)

    with open(log_path, 'a+', encoding='UTF-8') as fp:
        while True:
            line = ser.readline().strip()
            log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
            if len(log):
                fp.write(log + '\r\n')
                print(log)


def execute(ser):
    cmd = 'ps\n'
    # cmd = 'free\n'
    ser.write(cmd.encode())
    timer = Timer(15, execute, args=(serial,))
    timer.start()


if __name__ == '__main__':
    com = SerialReader.get_serial_com()
    serial = SerialReader.get_serial(com)
    # execute(serial)
    t = Thread(target=write_log, args=(serial,))
    t.start()
